package com.health.fragment.tijian;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.PersonalFileActivity.onFragmentSave;
import com.health.R;
import com.health.adapter.CheckBoxAdapter;
import com.health.adapter.RadioButtonAdapter;
import com.health.db.FDbManager;
import com.health.fragment.NovaFragment;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.ARCHIVE_CUSTOMERBASEINFO;
import com.health.tablebean.ARCHIVE_GENERALCONDITION;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.OLDER_SELFCAREABILITY;
import com.health.tablebean.SBCL_DATA;
import com.health.viewscontrols.tijian.TiJianActivity;
import com.health.viewscontrols.tijian.YBQK_ZiLiWenJuanActivity;
import com.health.tools.GlobalConts;
import com.health.view.spinner.NiceSpinner;
import com.health.widget.EditTextWithDate;
import com.health.widget.MyGridView;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.ExamHistoryActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * 健康体检 一般情况
 * 
 * @author 鹿云龙
 */
public class HealthTiJian_YbqkFragment extends NovaFragment implements onFragmentSave, OnClickListener {
	private final static int I_NULL = -1;
	/**
	 * from ==1 从数据库读取 from ==0数据库中没有数据
	 */
	private int acFrom;
	/**
	 * from ==1 从数据库读取 from ==0数据库中没有数据
	 */
	private int agFrom;
	private View baseView = null;
	private ARCHIVE_BASEINFO userInfo;// 基本信息

	private ARCHIVE_CUSTOMERBASEINFO acDB;// 健康体检_客户体检基本信息(症状)
	private ARCHIVE_GENERALCONDITION agDB;// 健康体检_一般状况(基本信息和老年人评估)
	private FDbManager fdbmanger = null;
	private Button btn_huxipinlv_more;
	/* 基本信息 */
	/** 体检日期 */
	private EditTextWithDate etCheckDate;
	/** 姓名 */
	private EditText etName;
	private NiceSpinner doctorSpinner;// 责任医生
	/* 一般状况-------------------------------------------- */
	/** cm腰围(保留两位小数) */
	private EditText etWaistline;
	/** 呼吸频率 */
	private EditText etBreathRate;
	/** 体温(保留两位小数) */
	public static EditText etTem;
	/** 身高(保留两位小数) */
	private EditText etHeight;
	/** 体重(保留两位小数) */
	private static EditText etWeight;
	/** bmi */
	private EditText etBMI;
	/** 脉率 */
	private static EditText etPulserate;
	/** 左侧高血压 */
	private static EditText etLeftHeight;
	/** 左侧低血压 */
	private static EditText etLeftPre;
	/** 右侧高血压 */
	private static EditText etRightHeight;
	/** 右侧低血压 */
	private static EditText etRightPre;

	private Button btn_tiwen_more;// 体温
	private Button btn_tizhong_more;// 体重
	private Button btn_mailv_more;// 脉率
	private Button btn_zuocexueya_more;// 左侧血压
	private Button btn_youcexueya_more;// 右侧血压
	/* -------------------------------------------------- */

	/** 老年人情感状态 */
	private MyGridView qingganGridView;
	private MyGridView gview;
	private CheckBoxAdapter zzAdapter;
	/**
	 * 老人健康自我评估
	 */
	private NiceSpinner niceSpinnerZiWoPingGu;// 自我健康评估
	private RadioButtonAdapter adapter_qg;// 情感状态
	private EditText etGloomyscore;// 老年人抑郁评分检查总分
	private Button startPingGu;// 老年人自理能力评估
	private NiceSpinner ziliPingguResult;// 老年人自理能力评估结果
	private MyGridView mgv_renzhigongneng;// 老年人认知功能
	private RadioButtonAdapter adapter_renZhiGongNeng;// 认知功能
	private EditText et_jianlizhili;// 简易智力状态检查总分
	String IDCARD;
	private Button refeshBtn;
	String strWhere = "IDCARD LIKE '" + NovaApplication.getUserInfo().getIDCARD() + "'";

	private int xy_result = -1;// 1左侧血压 2 右侧血压
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	private boolean flag_save = true;

	@Override
	public View findViews(LayoutInflater inflater) {
		baseView = inflater.inflate(R.layout.fragment_healthtijian_ybqk, null);
		findViews(baseView);

		GlobalConts.setMaxLength(3, etPulserate, etLeftHeight, etLeftPre, etRightHeight, etRightPre, etBreathRate);//
		GlobalConts.setMaxLength(5, et_jianlizhili, etGloomyscore);//
		GlobalConts.setMaxLength(6, etWaistline, etBMI, etWeight, etTem, etHeight, et_jianlizhili, etGloomyscore);
		return baseView;
	}

	private List<BD_DD_INFO> zilinengli;
	/** 计算BMI */
	private Button btn_jisuan;

	private void findViews(View baseView) {
		refeshBtn = (Button) baseView.findViewById(R.id.btn_refesh);
		refeshBtn.setOnClickListener(this);
		gview = (MyGridView) baseView.findViewById(R.id.gridView1);
		niceSpinnerZiWoPingGu = (NiceSpinner) baseView.findViewById(R.id.spinner_ziwopinggu);
		qingganGridView = (MyGridView) baseView.findViewById(R.id.qingganzhuangtai);
		fdbmanger = NovaApplication.fdbmanger;
		userInfo = NovaApplication.getUserInfo();
		IDCARD = NovaApplication.getUserInfo().getIDCARD();
		/* 基本信息--------- */
		etCheckDate = (EditTextWithDate) baseView.findViewById(R.id.check_date);
		etCheckDate.setBefore(new Date());
		etName = (EditText) baseView.findViewById(R.id.name);
		// etCheckDate = (EditText) baseView.findViewById(R.id.check_date);
		doctorSpinner = (NiceSpinner) baseView.findViewById(R.id.doctorid);
		/* 一般情况--------- */
		etBMI = (EditText) baseView.findViewById(R.id.et_bmi);
		etBreathRate = (EditText) baseView.findViewById(R.id.et_breath_rate);
		etHeight = (EditText) baseView.findViewById(R.id.et_height);
		etLeftHeight = (EditText) baseView.findViewById(R.id.et_left_h);
		etLeftPre = (EditText) baseView.findViewById(R.id.et_left_p);
		etPulserate = (EditText) baseView.findViewById(R.id.et_pulserate);
		etRightHeight = (EditText) baseView.findViewById(R.id.et_right_h);
		etRightPre = (EditText) baseView.findViewById(R.id.et_right_p);
		etTem = (EditText) baseView.findViewById(R.id.et_tem);
		etWaistline = (EditText) baseView.findViewById(R.id.et_waistline);
		etWeight = (EditText) baseView.findViewById(R.id.et_weight);
		etGloomyscore = (EditText) baseView.findViewById(R.id.et_gloomyscore);
		btn_huxipinlv_more = (Button) baseView.findViewById(R.id.btn_huxipinlv_more);
		startPingGu = (Button) baseView.findViewById(R.id.start_pinggu);
		ziliPingguResult = (NiceSpinner) baseView.findViewById(R.id.result_zili);
		mgv_renzhigongneng = (MyGridView) baseView.findViewById(R.id.mgv_renzhigongneng);
		et_jianlizhili = (EditText) baseView.findViewById(R.id.et_jianlizhili);

		btn_tiwen_more = (Button) baseView.findViewById(R.id.btn_tiwen_more);
		btn_tizhong_more = (Button) baseView.findViewById(R.id.btn_tizhong_more);
		btn_mailv_more = (Button) baseView.findViewById(R.id.btn_mailv_more);
		btn_zuocexueya_more = (Button) baseView.findViewById(R.id.btn_zuocexueya_more);
		btn_youcexueya_more = (Button) baseView.findViewById(R.id.btn_youcexueya_more);
		btn_jisuan = (Button) baseView.findViewById(R.id.btn_jisuan);
		btn_jisuan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setBMI();
			}
		});

	}

	public void setNiceSpinner() {
		zilinengli = FDbManager.getInstance(getActivity()).findAllByWhereInInfoDB(BD_DD_INFO.class,
				"PARENTID = 'DM100-03' order by cast(SORT as int) asc");
		List<String> myList2 = new ArrayList<String>();
		for (int i = 0; i < 4; i++) {
			myList2.add(zilinengli.get(i).getDATAINFO());
		}
		ziliPingguResult.attachDataSource(myList2);
	}

	/**
	 * 解析已有的症状数据，并初始化checkboxadapter
	 * 
	 * @author 鹿云龙
	 * 
	 * @date 2015年12月19日 下午1:40:41
	 */
	public void bindCheck(String symptom) {
		List<BD_DD_INFO> bds = fdbmanger.findAllByWhere(BD_DD_INFO.class, "ID=" + checkedIdsSql(symptom));
		ArrayList<Integer> checkedlist = new ArrayList<Integer>();
		for (BD_DD_INFO bd : bds) {
			int i = Integer.parseInt(bd.getSORT());
			checkedlist.add(i);
		}
	}

	@SuppressLint("UseSparseArrays")
	/**
	 * 绑定症状数据
	 * 
	 * @author 鹿云龙
	 * @date 2015年12月16日 下午4:54:17
	 */
	private void bindZhengZhuangData() {
		try {
			List<BD_DD_INFO> zhengZhuangList = FDbManager.getInstance(getActivity())
					.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID = 'DM100-01' order by cast(SORT as int) asc");
			zzAdapter = new CheckBoxAdapter(getActivity(), zhengZhuangList);
			zzAdapter.setOtherMaxLength(120);
			gview.setAdapter(zzAdapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<BD_DD_INFO> nsJianKangZiWo;

	/**
	 * 老人健康自我评估下拉框
	 */
	public void bindZiWoPingGu() {
		try {
			nsJianKangZiWo = FDbManager.getInstance(getActivity()).findAllByWhereInInfoDB(BD_DD_INFO.class,
					"PARENTID = 'DM100-02' order by cast(SORT as int) asc");
			niceSpinnerZiWoPingGu.attachDataSource(getDataInfo(nsJianKangZiWo));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void bindDdata(String flag, String str_where) {
		List<BD_DD_INFO> listZZs = fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
				str_where + " order by cast(SORT as int) asc");
		if (flag.equals("情感状况")) {

			adapter_qg = new RadioButtonAdapter(listZZs, getActivity());
			qingganGridView.setAdapter(adapter_qg);

			adapter_renZhiGongNeng = new RadioButtonAdapter(listZZs, getActivity());
			mgv_renzhigongneng.setAdapter(adapter_renZhiGongNeng);
		}
	}

	/**
	 * 获取下拉框中需要的数据的信息
	 * 
	 * @param datas
	 * @return
	 * @author 鹿云龙
	 * @date 2015年12月16日 下午3:47:00
	 */
	private ArrayList<String> getDataInfo(List<BD_DD_INFO> datas) {
		ArrayList<String> infos = new ArrayList<String>();
		for (BD_DD_INFO bd : datas) {
			infos.add(bd.getDATAINFO());
		}
		return infos;
	}

	@Override
	public void setupView(View view) {
	}

	@Override
	public void addListener() {

		startPingGu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), YBQK_ZiLiWenJuanActivity.class);
				startActivity(intent);
			}
		});
		btn_huxipinlv_more.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayList<BD_DD_INFO> aaa = zzAdapter.getCheckedBD_DD_INFO();
			}
		});

		btn_tiwen_more.setOnClickListener(this);
		btn_tizhong_more.setOnClickListener(this);
		btn_mailv_more.setOnClickListener(this);
		btn_zuocexueya_more.setOnClickListener(this);
		btn_youcexueya_more.setOnClickListener(this);
	}

	@Override
	public void setData() {
		setNiceSpinner();
		GlobalConts.doctorList(doctorSpinner);
		bindZhengZhuangData();
		bindZiWoPingGu();

		bindDdata("情感状况", "PARENTID = 'DM100-04'");
		initData();
		setDateCheck();

	}

	@Override
	public void onResume() {
		super.onResume();
		// setData();
	}

	private void setDateCheck() {
		// 体温
		GlobalConts.keep2decimal(etTem);
		GlobalConts.checkNum(getActivity(), etTem, 37.3, 36, 99);

		// 身高 GlobalConts.checkNum(etHeight, 300, 1);
		GlobalConts.checkNumOrange(getActivity(), etHeight, 300, 1);
		// 体重
		GlobalConts.keep2decimal(etWeight);
		GlobalConts.keep2decimal(etBMI);
		GlobalConts.checkNum(getActivity(), etWeight, 100, 1, 999);
		GlobalConts.checkNum(getActivity(), etBMI, 999, 0, 999);
		// 腰围
		GlobalConts.keep2decimal(etWaistline);
		GlobalConts.checkNumOrange(getActivity(), etWaistline, 999, 1);

		// 呼吸频率
		GlobalConts.checkNum(getActivity(), etBreathRate, 100, 10, 999);//
		// 脉率
		GlobalConts.checkNum(getActivity(), etPulserate, 100, 50, 999);
		// 左侧 高血压
		GlobalConts.checkNum(getActivity(), etLeftHeight, 139, 90, 300);
		// 左侧 低血压
		GlobalConts.checkNum(getActivity(), etLeftPre, 89, 60, 299);

		// 右侧 高血压
		GlobalConts.checkNum(getActivity(), etRightHeight, 139, 90, 300);
		// 右侧 低血压
		GlobalConts.checkNum(getActivity(), etRightPre, 89, 60, 299);
	}

	/**
	 * 初始化控件数据
	 * 
	 * @author 鹿云龙
	 * @date 2015年12月21日 上午10:10:19
	 */
	public void initData() {
		try {
			// TODO 初始化
			List<ARCHIVE_CUSTOMERBASEINFO> acs = fdbmanger.findAllByWhere(ARCHIVE_CUSTOMERBASEINFO.class,
					"IDCARD = '" + userInfo.getIDCARD() + "'");
			List<ARCHIVE_GENERALCONDITION> ags = fdbmanger.findAllByWhere(ARCHIVE_GENERALCONDITION.class,
					"IDCARD = '" + userInfo.getIDCARD() + "'");
			etName.setText(userInfo.getCUSTOMERNAME());
			if (acs.size() > 0) {
				acFrom = 1;
				ARCHIVE_CUSTOMERBASEINFO ac = acs.get(acs.size() - 1);
				for (int i = 0; i < NovaApplication.getDoctorList().size(); i++) {
					if (NovaApplication.getDoctorList().get(i).getUSER_ID().equals(ac.getLAST_UPDATE_BY())) {
						doctorSpinner.setSelectedIndex(i);
					}

				}

				if (!TextUtils.isEmpty(ac.getSYMPTOM())) {
					if (ac.getSYMPTOM().contains("DM100-01_0")) {
						zzAdapter.setWuZhengZhuangChecked(true);
					}
					zzAdapter.setChecked(ac.getSYMPTOM());
					String srr = ac.getOTHER();
					zzAdapter.setOther(ac.getOTHER());
				}

				if (ac.getCHECKDATE() != null) {
					try {
						etCheckDate.setText(dateFormat.format(ac.getCHECKDATE()));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			} else {
				ARCHIVE_CUSTOMERBASEINFO ac = new ARCHIVE_CUSTOMERBASEINFO();
				etCheckDate.setText(dateFormat.format(new Date()));
				for (int i = 0; i < NovaApplication.getDoctorList().size(); i++) {
					if (userInfo.getCREATED_BY().equals(NovaApplication.getDoctorList().get(i).getUSER_ID())) {
						doctorSpinner.setSelectedIndex(i);
					}

				}
				String str_ed_time1_start = etCheckDate.getText().toString();
				if (!TextUtils.isEmpty(str_ed_time1_start)) {
					try {
						ac.setCHECKDATE((Date) dateFormat.parse(str_ed_time1_start));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				ac.setCREATED_DATE(GlobalConts.dateFormat.parse(GlobalConts.dateFormat.format(new Date())));// 创建时间
				ac.setDOCTOR(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());// 主治医生（体检时的主治医生）
				ac.setCREATED_BY(userInfo.getCREATED_BY());
				ac.setCREATER(userInfo.getCREATER());
				ac.setCREATEORG(userInfo.getCREATEORG());
				ac.setIDCARD(userInfo.getIDCARD());
				NovaApplication.fdbmanger.save(ac);
				acFrom = 1;
			}
			List<SBCL_DATA> twList = fdbmanger.findAllByWhere(SBCL_DATA.class, "IDCARD = '" + userInfo.getIDCARD()
					+ "' and " + "(CL_TYPE='体温' or CL_TYPE='表面温度')" + " and " + "CL_TIME like '" + dateFormat.format(new Date()) + "%'");
			List<SBCL_DATA> mlList = fdbmanger.findAllByWhere(SBCL_DATA.class, "IDCARD = '" + userInfo.getIDCARD()
					+ "' and " + "CL_TYPE='脉率'" + " and " + "CL_TIME like '" + dateFormat.format(new Date()) + "%'");
			List<SBCL_DATA> gyList = fdbmanger.findAllByWhere(SBCL_DATA.class, "IDCARD = '" + userInfo.getIDCARD()
					+ "' and " + "CL_TYPE='高压'" + " and " + "CL_TIME like '" + dateFormat.format(new Date()) + "%'");
			List<SBCL_DATA> dyList = fdbmanger.findAllByWhere(SBCL_DATA.class, "IDCARD = '" + userInfo.getIDCARD()
					+ "' and " + "CL_TYPE='低压'" + " and " + "CL_TIME like '" + dateFormat.format(new Date()) + "%'");
			List<SBCL_DATA> tzList = fdbmanger.findAllByWhere(SBCL_DATA.class, "IDCARD = '" + userInfo.getIDCARD()
					+ "' and " + "CL_TYPE='体重'" + " and " + "CL_TIME like '" + dateFormat.format(new Date()) + "%'",
					"CL_TIME desc");
			if (ags.size() > 0) {
				agFrom = 1;
				ARCHIVE_GENERALCONDITION ag = ags.get(ags.size() - 1);
				/* 一般状况-------------------------------------------- */
				if (TextUtils.isEmpty(ag.getWAISTLINE())) {
					etWaistline.setText("");
				} else {
					etWaistline.setText(ag.getWAISTLINE() + "");
				}
				if (TextUtils.isEmpty(ag.getBREATH_RATE())) {
					etBreathRate.setText("");
				} else {
					etBreathRate.setText(ag.getBREATH_RATE() + "");
				}

				if (!TextUtils.isEmpty(ag.getTEM())) {
					etTem.setText(ag.getTEM() + "");
				} else {
					if (twList.size() > 0) {
						etTem.setText(twList.get(twList.size() - 1).getCL_VALUE().split("℃")[0]);
					}else{
						etTem.setText("");
					}
				}
				if (TextUtils.isEmpty(ag.getHEIGHT())) {
					etHeight.setText("");
				} else {
					etHeight.setText(ag.getHEIGHT() + "");
				}

				String dataWeight = "";
				if (tzList != null && !tzList.isEmpty()) {
					dataWeight = tzList.get(0).getCL_VALUE();
				}
				if (TextUtils.isEmpty(ag.getBMI())) {
					etBMI.setText("");
				} else {
					etBMI.setText(ag.getBMI() + "");
				}
				if (!TextUtils.isEmpty(ag.getWEIGHT())) {
					etWeight.setText(ag.getWEIGHT() + "");
				} else {
					if (!TextUtils.isEmpty(dataWeight)) {
						etWeight.setText(dataWeight.split("Kg")[0]);
					} else {
						etWeight.setText("");
					}
				}

				if (!TextUtils.isEmpty(ag.getPULSERATE())) {
					etPulserate.setText(ag.getPULSERATE() + "");
				} else {
					if (mlList.size() > 0) {
						String value = mlList.get(mlList.size() - 1).getCL_VALUE();
						if (value.contains("次/分")) {
							etPulserate.setText(value.split("次/分")[0]);
						} else if (value.contains("bpm")) {
							etPulserate.setText(value.split("bpm")[0]);
						}else{
							etPulserate.setText("");
						}
					}
				}
				if (!TextUtils.isEmpty(ag.getLEFTHEIGHT())) {
					etLeftHeight.setText(ag.getLEFTHEIGHT() + "");
				} else{
					if (gyList.size() > 0) {
						etLeftHeight.setText(gyList.get(gyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
					}else{
						etLeftHeight.setText("");
					}
				} 
				if (!TextUtils.isEmpty(ag.getLEFTPRE())) {
					etLeftPre.setText(ag.getLEFTPRE() + "");
				} else{
					if (dyList.size() > 0) {
						etLeftPre.setText(dyList.get(dyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
					}else{
						etLeftPre.setText("");
					}
				} 
				if (!TextUtils.isEmpty(ag.getRIGHTHEIGHT())) {
					etRightHeight.setText(ag.getRIGHTHEIGHT() + "");
				} else {
					if (gyList.size() > 0) {
						etRightHeight.setText(gyList.get(gyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
					}else{
						etRightHeight.setText("");
					}
				}
				if (!TextUtils.isEmpty(ag.getRIGHTPRE())) {
					etRightPre.setText(ag.getRIGHTPRE() + "");
				} else {
					if (dyList.size() > 0) {
						etRightPre.setText(dyList.get(dyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
					}else{
						etRightPre.setText("");
					}
				}

				etGloomyscore.setText(ag.getGLOOMYSCORE() + "");
				// System.out.println(ag.getOLD_HEALTHSTATUS());
				niceSpinnerZiWoPingGu.setSelectedIndex(getListIndex(ag.getOLD_HEALTHSTATUS(), nsJianKangZiWo));
				adapter_renZhiGongNeng.setChecked(ag.getOLD_RECOGNISE());
				// TODO
				// try{
				adapter_qg.setChecked(ag.getOLD_EMOTION());
				et_jianlizhili.setText(ag.getINTELSCORE() + "");
				int i = getListIndex(ag.getOLD_SELFCAREABILITY(), zilinengli);
				System.out.println(i);
				ziliPingguResult.setSelectedIndex(getListIndex(ag.getOLD_SELFCAREABILITY(), zilinengli));

			} else {
				// ;
				// k
				// List<SBCL_DATA> tiZhongDatas =
				// NovaApplication.fdbmanger.findAllBTByWhere(SBCL_DATA.class,
				// "CL_TYPE = '" + "体重" + "' AND IDCARD = '" + IDCARD + "'",
				// "CL_TIME desc");
				String dataWeight = "";
				if (tzList != null && !tzList.isEmpty()) {
					dataWeight = tzList.get(0).getCL_VALUE();
				}

				if (!TextUtils.isEmpty(dataWeight)) {
					etWeight.setText(dataWeight.split("Kg")[0]);
				} else {
					etWeight.setText("");
				}
				if (twList.size() > 0) {
					etTem.setText(twList.get(twList.size() - 1).getCL_VALUE().split("℃")[0]);
				}
				if (mlList.size() > 0) {
					String value = mlList.get(mlList.size() - 1).getCL_VALUE();
					if (value.contains("次/分")) {
						etPulserate.setText(value.split("次/分")[0]);
					} else if (value.contains("bpm")) {
						etPulserate.setText(value.split("bpm")[0]);
					}
				}
				if (gyList.size() > 0) {
					etLeftHeight.setText(gyList.get(gyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
				}
				if (dyList.size() > 0) {
					etLeftPre.setText(dyList.get(dyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
				}
				if (gyList.size() > 0) {
					etRightHeight.setText(gyList.get(gyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
				}
				if (dyList.size() > 0) {
					etRightPre.setText(dyList.get(dyList.size() - 1).getCL_VALUE().split("mmHg")[0]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		boolean older = isOlder();
		// TODO
		niceSpinnerZiWoPingGu.setEnabled(older);
		niceSpinnerZiWoPingGu.setClickable(older);
		// niceSpinnerZiWoPingGu.setText("");

		ziliPingguResult.setEnabled(older);
		ziliPingguResult.setClickable(older);
		// ziliPingguResult.setText("");

		startPingGu.setEnabled(older);
		et_jianlizhili.setEnabled(older);
		qingganGridView.setDisable(!older);
		etGloomyscore.setEnabled(older);
		mgv_renzhigongneng.setDisable(!older);
		changeBMI();
	}

	/**
	 * 身高或者体重改变时，BMI的值随之发生改变
	 **/
	private void changeBMI() {
		etHeight.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!TextUtils.isEmpty(etWeight.getText())) {
					setBMI();
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		etWeight.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!TextUtils.isEmpty(etHeight.getText())) {
					setBMI();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	/**
	 * 保存数据
	 * 
	 * @author 鹿云龙
	 * @date 2015年12月21日 上午10:49:31
	 */
	private void saveData() {
		agDB = new ARCHIVE_GENERALCONDITION();
		acDB = new ARCHIVE_CUSTOMERBASEINFO();
		String WAISTLINE = etWaistline.getText().toString();
		// 数据验证取消
		if (TextUtils.isEmpty(WAISTLINE)) {
			flag_save = false;
			etWaistline.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写腰围");
			agDB.setWAISTLINE("");
			return;

		} else {
			if (!GlobalConts.getCheckNumOrangeBoolean(getActivity(), etWaistline, 999, 1)) {
				flag_save = false;
				etWaistline.setBackgroundColor(Color.YELLOW);
				((TiJianActivity) getActivity()).showTextDialog("腰围数据不合理，保存失败");
				return;
			}
			etWaistline.setBackgroundColor(Color.WHITE);
			agDB.setWAISTLINE(WAISTLINE);
		}

		String BREATH_RATE = etBreathRate.getText().toString();
		if (TextUtils.isEmpty(BREATH_RATE)) {
			flag_save = false;
			etBreathRate.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写呼吸频率");
			agDB.setBREATH_RATE("");
			return;

		} else {
			etBreathRate.setBackgroundColor(Color.WHITE);
			agDB.setBREATH_RATE(BREATH_RATE);
		}

		// 体温
		String TEM = etTem.getText().toString();
		if (TextUtils.isEmpty(TEM)) {
			flag_save = false;
			etTem.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写体温");
			return;
		} else {
			if (!GlobalConts.isRightNumber("体温", TEM)) {
				flag_save = false;
				etTem.setBackgroundColor(Color.YELLOW);
				((TiJianActivity) getActivity()).showTextDialog("体温数据不合理，保存失败");
				return;
			}
			etTem.setBackgroundColor(Color.WHITE);
			agDB.setTEM(TEM);
		}

		// 身高
		String HEIGHT = etHeight.getText().toString();
		if (TextUtils.isEmpty(HEIGHT)) {
			flag_save = false;
			etHeight.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写身高");
			agDB.setHEIGHT("");
			return;

		} else {
			if (!GlobalConts.isRightNumber("身高", HEIGHT)) {
				flag_save = false;
				etHeight.setBackgroundColor(Color.YELLOW);
				((TiJianActivity) getActivity()).showTextDialog("身高数据不合理，保存失败");
				return;
			}
			etHeight.setBackgroundColor(Color.WHITE);
			agDB.setHEIGHT(HEIGHT);
		}

		// 体重
		String WEIGHT = etWeight.getText().toString();
		if (TextUtils.isEmpty(WEIGHT)) {
			flag_save = false;
			etWeight.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写体重");
			agDB.setWEIGHT("");
			return;

		} else {
			if (!GlobalConts.isRightNumber("体重", WEIGHT)) {
				flag_save = false;
				etWeight.setBackgroundColor(Color.YELLOW);
				((TiJianActivity) getActivity()).showTextDialog("体重数据不合理，保存失败");
				return;
			}
			etWeight.setBackgroundColor(Color.WHITE);
			agDB.setWEIGHT(WEIGHT);
		}

		setBMI();
		String BMI = etBMI.getText().toString();
		if (!TextUtils.isEmpty(BMI)) {
			if (!GlobalConts.isRightNumber("体质指数", BMI)) {
				flag_save = false;
				((TiJianActivity) getActivity()).showTextDialog("BMI数据不合理，保存失败");
				return;
			}
		}
		agDB.setBMI(BMI);

		// 脉率
		String PULSERATE = etPulserate.getText().toString();
		if (TextUtils.isEmpty(PULSERATE)) {
			flag_save = false;
			etPulserate.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写脉率");
			return;
		} else {
			if (!GlobalConts.isRightNumber("脉率", PULSERATE)) {
				flag_save = false;
				etPulserate.setBackgroundColor(Color.YELLOW);
				((TiJianActivity) getActivity()).showTextDialog("脉率数据不合理，保存失败");
				return;
			}
			etPulserate.setBackgroundColor(Color.WHITE);
			agDB.setPULSERATE(PULSERATE);
		}

		// 血压
		String LEFTHEIGHT = etLeftHeight.getText().toString();
		String LEFTPRE = etLeftPre.getText().toString();
		String RIGHTHEIGHT = etRightHeight.getText().toString();
		String RIGHTPRE = etRightPre.getText().toString();
		if (TextUtils.isEmpty(LEFTHEIGHT) && TextUtils.isEmpty(LEFTPRE) && TextUtils.isEmpty(RIGHTHEIGHT)
				&& TextUtils.isEmpty(RIGHTPRE)) {
			flag_save = false;
			etLeftHeight.setBackgroundColor(Color.YELLOW);
			etLeftPre.setBackgroundColor(Color.YELLOW);
			etRightHeight.setBackgroundColor(Color.YELLOW);
			etRightPre.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请至少填写一侧血压");
			return;
		}else if ((!TextUtils.isEmpty(LEFTHEIGHT) && TextUtils.isEmpty(LEFTPRE))||(TextUtils.isEmpty(LEFTHEIGHT) && !TextUtils.isEmpty(LEFTPRE))){
			flag_save = false;
			etLeftHeight.setBackgroundColor(Color.YELLOW);
			etLeftPre.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写完整高压和低压");
			return;
		}else if ((!TextUtils.isEmpty(RIGHTHEIGHT) && TextUtils.isEmpty(RIGHTPRE))||(TextUtils.isEmpty(RIGHTHEIGHT) && !TextUtils.isEmpty(RIGHTPRE))){
			flag_save = false;
			etRightHeight.setBackgroundColor(Color.YELLOW);
			etRightPre.setBackgroundColor(Color.YELLOW);
			((TiJianActivity) getActivity()).showTextDialog("请填写完整高压和低压");
			return;
		}else {
			etLeftHeight.setBackgroundColor(Color.WHITE);
			etLeftPre.setBackgroundColor(Color.WHITE);
			etRightHeight.setBackgroundColor(Color.WHITE);
			etRightPre.setBackgroundColor(Color.WHITE);
		}

		agDB.setLEFTHEIGHT(LEFTHEIGHT);
		agDB.setLEFTPRE(LEFTPRE);
		agDB.setRIGHTHEIGHT(RIGHTHEIGHT);
		agDB.setRIGHTPRE(RIGHTPRE);

		// if(!GlobalConts.getCheckNumOrangeBoolean(getActivity(), etBreathRate,
		// 100, 50)){
		// ((TiJianActivity) getActivity()).showTextDialog("呼吸率数据不合理，保存失败");
		// return;
		// }
		// if(!GlobalConts.getCheckNumOrangeBoolean(getActivity(), etBreathRate,
		// 100, 50)){
		// ((TiJianActivity) getActivity()).showTextDialog("呼吸率数据不合理，保存失败");
		// return;
		// }
		if(!TextUtils.isEmpty(LEFTHEIGHT)&&!TextUtils.isEmpty(LEFTPRE)){
			if (!GlobalConts.isRightNumber("血压", LEFTHEIGHT)) {
				flag_save = false;
				((TiJianActivity) getActivity()).showTextDialog("左侧高血压数据不合理，保存失败");
				return;
			}
			if (!GlobalConts.isRightNumber("血压", LEFTPRE)) {
				flag_save = false;
				((TiJianActivity) getActivity()).showTextDialog("左侧低血压数据不合理，保存失败");
				return;
			}
		}

		if(!TextUtils.isEmpty(RIGHTHEIGHT)&&!TextUtils.isEmpty(RIGHTPRE)){
			if (!GlobalConts.isRightNumber("血压", RIGHTHEIGHT)) {
				flag_save = false;
				((TiJianActivity) getActivity()).showTextDialog("右侧高血压数据不合理，保存失败");
				return;
			}
			if (!GlobalConts.isRightNumber("血压", RIGHTPRE)) {
				flag_save = false;
				((TiJianActivity) getActivity()).showTextDialog("右侧低血压数据不合理，保存失败");
				return;
			}
		}



		String GLOOMYSCORE = etGloomyscore.getText().toString();
		agDB.setGLOOMYSCORE(GLOOMYSCORE);// 老人抑郁

		agDB.setOLD_EMOTION(adapter_qg.getChecked()); // 老年人情感状态1:粗筛阴性,2:粗筛阳性
		agDB.setOLD_RECOGNISE(adapter_renZhiGongNeng.getChecked());// 认知功能
		agDB.setOLD_HEALTHSTATUS(nsJianKangZiWo.get(niceSpinnerZiWoPingGu.getSelectedIndex()).getID());// 老年人健康自我评估

		agDB.setIDCARD(userInfo.getIDCARD());
		String strintelscore = et_jianlizhili.getText().toString();
		agDB.setINTELSCORE(strintelscore);
		agDB.setOLD_SELFCAREABILITY(zilinengli.get(ziliPingguResult.getSelectedIndex()).getID());
		String str_ed_time1_start = etCheckDate.getText().toString();
		if (!TextUtils.isEmpty(str_ed_time1_start)) {
			try {
				acDB.setCHECKDATE((Date) dateFormat.parse(str_ed_time1_start));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (acFrom == 1) {
			acDB.setLAST_UPDATE_BY(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());
			acDB.setLAST_UPDATE_DATE(new Date());
			acDB.setMODIFIED(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());
			acDB.setUPDATEORG(userInfo.getCREATEORG());
			acDB.setDOCTOR(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());// 主治医生（体检时的主治医生）
		} else {
			acDB.setCREATED_DATE(new Date());// 创建时间
			acDB.setDOCTOR(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());// 主治医生（体检时的主治医生）
			acDB.setCREATED_BY(userInfo.getCREATED_BY());
			acDB.setCREATER(userInfo.getCREATER());
			acDB.setCREATEORG(userInfo.getCREATEORG());
			acDB.setLAST_UPDATE_BY(NovaApplication.getDoctorList().get(doctorSpinner.getSelectedIndex()).getUSER_ID());
			acDB.setLAST_UPDATE_DATE(new Date());
		}

		acDB.setIDCARD(userInfo.getIDCARD());// 身份证号码
		// acdatabase.setIS_DEL(iS_DEL);// 是否删除 Y是逻辑删除，N是逻辑删除 默认值是N
		// acdatabase.setLAST_UPDate_BY(lAST_UPDate_BY);// 修改人
		// acdatabase.setLAST_UPDate_Date(lAST_UPDate_Date);// 修改时间
		// acDB.setOLDERID(oLDERID);// 老年人自我评估能力

		acDB.setSYMPTOM(zzAdapter.getCheckedIdsStr());// 症状
		String sss = zzAdapter.getOther();
		System.out.println(sss);
		acDB.setOTHER(zzAdapter.getOther());// 其他
		acDB.setIS_UPDATE("Y");
		// zhengzhuangadapter.getCheckedIdsStr();

		if (agFrom == 0) {
			FDbManager.getInstance(getActivity()).save(agDB);
			agFrom = 1;
		} else {
			FDbManager.getInstance(getActivity()).updata(agDB, "IDCARD='" + userInfo.getIDCARD() + "'");
		}
		if (acFrom == 0) {
			FDbManager.getInstance(getActivity()).save(acDB);
			acFrom = 1;
		} else {
			FDbManager.getInstance(getActivity()).updata(acDB, "IDCARD='" + userInfo.getIDCARD() + "'");
		}
		flag_save = true;
	}

	public int getListIndex(String id, List<BD_DD_INFO> bds) {
		int index = 0;
		try {
			for (int i = 0; i < bds.size(); i++) {
				if (id.equals(bds.get(i).getID())) {
					index = i;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return index;
	}

	/**
	 * 字符串转换"1,2,3,4,5" --> "'1','2','3','4','5'"
	 * 
	 * @param symptom
	 * @return
	 * @author 鹿云龙
	 * @date 2015年12月19日 下午2:49:23
	 */
	public String checkedIdsSql(String symptom) {
		String[] idarr = symptom.split(",");
		String sql = "";
		for (String id : idarr) {
			sql += "'" + id + "',";
		}
		sql = sql.substring(0, sql.length() - 1);
		System.out.println(sql);
		return sql;
	}

	@Override
	public void save() {
		saveData();
		if (flag_save) {
			((TiJianActivity) getActivity()).showTextDialog("保存成功");
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		List<OLDER_SELFCAREABILITY> list = fdbmanger.findAllByWhere(OLDER_SELFCAREABILITY.class,
				"IDCARD='" + IDCARD + "'");
		if (list.size() > 0) {
			OLDER_SELFCAREABILITY older_SELFCAREABILITY1 = list.get(0);
			int score = Integer.parseInt(older_SELFCAREABILITY1.getTOTALSCORE());
			if (score >= 0 && score <= 3) {
				ziliPingguResult.setSelectedIndex(0);
			} else if (score >= 4 && score <= 8) {
				ziliPingguResult.setSelectedIndex(1);
			} else if (score >= 9 && score <= 18) {
				ziliPingguResult.setSelectedIndex(2);
			} else if (score >= 19) {
				ziliPingguResult.setSelectedIndex(3);
			}
			// ziliPingguResult.setEnabled(false);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(getActivity(), ExamHistoryActivity.class);
		int id = v.getId();
		if (id == R.id.btn_refesh) {
			// 已隐藏
			List<SBCL_DATA> dataList = fdbmanger.findAllByWhere(SBCL_DATA.class, strWhere);
			if (dataList.size() == 0) {
				return;
			}
			String tiwen = "";
			String mailv = "";
			String gaoya = "";
			String diya = "";
			String xuetang = "";
			String tizhong = "";
			for (SBCL_DATA data : dataList) {
				String value = data.getCL_VALUE();
				switch (data.getCL_TYPE()) {
				case BluetoothConstant.TIWEN_TYPENAME:
					tiwen = value.split("℃")[0];
					break;
				case BluetoothConstant.TIZHONG_TYPENAME:
					mailv = value.split("Kg")[0];
					break;
				case "脉率":
					if (value.contains("次/分")) {
						mailv = value.split("次/分")[0];
					} else if (value.contains("bpm")) {
						mailv = value.split("bpm")[0];
					}
					break;

				case "高压":
					gaoya = value.split("mmHg")[0];
					break;

				case "低压":
					diya = value.split("mmHg")[0];
					break;
				case BluetoothConstant.XUEYANG_TYPENAME:
					xuetang = value.split("mmol/L")[0];
					break;

				default:
					break;

				}
			}
			etTem.setText(tiwen);
			etPulserate.setText(mailv);
			etLeftHeight.setText(gaoya);
			etRightHeight.setText(gaoya);
			etLeftPre.setText(diya);
			etRightPre.setText(diya);
			NovaApplication.xuetang = xuetang;
		} else if (id == R.id.btn_tiwen_more) {
			intent.putExtra("flag", "体温");
			getActivity().startActivityForResult(intent, GlobalConts.RequestTiwen);
		} else if (id == R.id.btn_tizhong_more) {
			intent.putExtra("flag", "体重");
			getActivity().startActivityForResult(intent, GlobalConts.RequestTizhong);
		} else if (id == R.id.btn_mailv_more) {
			intent.putExtra("flag", "脉率");
			getActivity().startActivityForResult(intent, GlobalConts.RequestMaiLv);
		} else if (id == R.id.btn_zuocexueya_more) {
			xy_result = 1;
			intent.putExtra("flag", "血压");
			getActivity().startActivityForResult(intent, GlobalConts.RequestXueya);
		} else if (id == R.id.btn_youcexueya_more) {
			xy_result = 2;
			intent.putExtra("flag", "血压");
			getActivity().startActivityForResult(intent, GlobalConts.RequestXueya);
		} else {
		}

	}

	@Override
	public void setXueya(String gaoya, String diya, String mailv) {
		Log.e("yibanqignk setXueya", gaoya + "\n" + diya + "\n" + mailv);
		if (xy_result == 1) {
			etLeftHeight.setText(gaoya);
			etLeftPre.setText(diya);
		} else if (xy_result == 2) {
			etRightHeight.setText(gaoya);
			etRightPre.setText(diya);
		}
	}

	public boolean isOlder() {
		userInfo = NovaApplication.getUserInfo();
		List<String> popList = new ArrayList<String>();
		if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
			String popStr = NovaApplication.getUserInfo().getPOPULATION_TYPE();
			String[] pops = popStr.split(",");
			popList = Arrays.asList(pops);
		}
		return popList.contains("4");
	}

	@Override
	public void setTiWen(String tiwen) {
		etTem.setText(tiwen);
	}

	// 显示体温
	public static void showTW(String tiwen) {
		if (etTem != null && !TextUtils.isEmpty(tiwen)) {
			etTem.setText(tiwen);
		}
	}

	// 显示体重
	public static void showTZ(String tz) {
		if (etWeight != null && !TextUtils.isEmpty(tz)) {
			etWeight.setText(tz);
		}
	}

	// 显示脉率
	public static void showML(String ml) {
		if (etPulserate != null && !TextUtils.isEmpty(ml)) {
			etPulserate.setText(ml);
		}
	}

	// 显示血压
	public static void showXY(String gaoya, String diya, String ml) {
		if (!TextUtils.isEmpty(gaoya)) {
			if (etLeftHeight != null && etLeftPre != null) {
				etLeftHeight.setText(gaoya);
				etLeftPre.setText(diya);
			}
			if (etRightHeight != null && etRightPre != null) {
				etRightHeight.setText(gaoya);
				etRightPre.setText(diya);
			}
			if (etPulserate != null && !TextUtils.isEmpty(ml)) {
				etPulserate.setText(ml);
			}

		}
	}

	@Override
	public void setTizhong(String value) {
		etWeight.setText(value);

	}

	@Override
	public void setMaiLv(String mailv) {
		etPulserate.setText(mailv);
	}

	@Override
	public void onDestroy() {
		saveData();
		super.onDestroy();
	}

	/**
	 * 设置BMI
	 * 
	 * @author 王婷婷
	 * @date 2017年4月5日 上午10:48:51
	 */
	private void setBMI() {
		try {
			if (etHeight.getText().toString().isEmpty() || etHeight.getText().toString().isEmpty()) {
				return;
			}

			double dh = Double.parseDouble(etHeight.getText().toString()) / 100;
			double dw = Double.parseDouble(etWeight.getText().toString());

			java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");

			etBMI.setText(df.format(GlobalConts.getBMI(dh, dw)) + "");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}